from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.db import IntegrityError
from django.http import HttpResponse,HttpResponseRedirect
from django.views.decorators import csrf
from assets import models
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
from django.core.exceptions import ValidationError
from django import forms
from django.contrib.auth.decorators import login_required
from IPy import IP
from django.contrib import messages
import xlrd
from xlrd import xldate_as_tuple
from datetime import datetime,date


def validate_excel(value):
    if value.name.split('.')[-1] not in ['xls','xlsx']:
        raise ValidationError(_('Invalid File Type: %(value)s'),params={'value': value},)

class UploadExcelForm(forms.Form):
    excel = forms.FileField(validators=[validate_excel])

@login_required(login_url='/login/')
def serverimport(request):
    if request.POST:
      form = UploadExcelForm(request.POST, request.FILES)
      if form.is_valid():
        wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
        table = wb.sheets()[0]
        row = table.nrows
        for i in range(1, row):
            name = table.cell(i,0).value
            name = name.strip('\n')
            sn = table.cell(i,1).value
            sn = sn.strip('\n')
            business_unit_text = table.cell(i,2).value
            manufacturer = table.cell(i,3).value
            modelnumber = table.cell(i,4).value
            status_text = table.cell(i,5).value
            server_type_text = table.cell(i,6).value
            idc = table.cell(i,7).value
            machineRoom = table.cell(i,8).value
            cabinet = table.cell(i,9).value
            high = table.cell(i,10).value
            manage_ip = table.cell(i,11).value
            operation = table.cell(i,12).value
            reason = table.cell(i,13).value
            memo = table.cell(i,14).value
            if business_unit_text == u'领骏':
                business_unit=0
            elif business_unit_text == u'驰联':
                business_unit=1
            if status_text == u'运营':
                status=0
            elif status_text == u'闲置':
                status=1
            elif status_text == u'待启用':
                status=2
            elif status_text == u'故障':
                status=3
            elif status_text == u'备用':
                status=4        
            if server_type_text == u'PC机':
                server_type=0
            elif server_type_text == u'服务器':
                server_type=1
            asset = models.Asset()
            if name:
                try:
                    tempserver = get_object_or_404(models.Asset,name=name)
                except:
                    asset.name=name    
                else:
                    messages.error(request,'第%d行数据导入失败,固资号已经存在' %i)
                    return HttpResponseRedirect('/serverimport')
            else:
                messages.error(request,'第%d行数据导入失败,固资号不能为空' %i)
                return HttpResponseRedirect('/serverimport')
            if sn:
                try:
                    tempserver = get_object_or_404(models.Asset,sn=sn)
                except:
                    asset.sn=sn    
                else:
                    messages.error(request,'第%d行数据导入失败,固资号已经存在' %i)
                    return HttpResponseRedirect('/serverimport')
            else:
                messages.error(request,'第%d行数据导入失败,SN不能为空' %i)
                return HttpResponseRedirect('/serverimport')           
            if idc:
                try:
                    idc_name = models.DataCenter.objects.get(name=idc)
                except:
                    messages.error(request,'第%d行数据导入失败,机房不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.idc = idc_name
            else:
                asset.idc = None            
            if machineRoom:
                try:
                    machineRoom_name = models.MachineRoom.objects.get(name=machineRoom)
                except:
                    messages.error(request,'第%d行数据导入失败,机房管理单元不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.machineRoom = machineRoom_name
            else:
                asset.machineRoom = None        
            if cabinet:
                try:
                    cabinet_name = models.Cabinet.objects.get(name=cabinet,machineroom = machineRoom_name)
                except:
                    messages.error(request,'第%d行数据导入失败,所在机房机架不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.cabinet = cabinet_name
            else:
                asset.cabinet = None        
            if modelnumber:
                try:
                    modelnumber_name = models.Modelnumber.objects.get(name=modelnumber)
                except:
                    messages.error(request,'第%d行数据导入失败,型号不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.modelnumber = modelnumber_name
            else:
                asset.modelnumber = None        
            if manufacturer:
                try:
                    manufacturer_name = models.Manufacturer.objects.get(name=manufacturer)
                except:
                    messages.error(request,'第%d行数据导入失败,厂商不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.manufacturer = manufacturer_name
            else:
                asset.manufacturer = None        
            if operation:
                try:
                    operation_name = User.objects.get(username=operation)
                except:
                    messages.error(request,'第%d行数据导入失败,维护人不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/serverimport')
                else:
                    asset.operation = operation_name
            else:
                asset.operation = None
            if manage_ip:
                asset.manage_ip = manage_ip
            else:
                asset.manage_ip = None
            asset.asset_type = 'server'
            asset.business_unit=business_unit
            asset.status=status
            asset.high=high
            asset.memo=memo
            asset.save()
            server = models.Server(asset=asset,server_type=server_type)
            server.save()
            detail=u'服务器导入'
            eventlog = models.EventLog(asset=asset,event_type=0,reason=reason,detail=detail,user=request.user)
            eventlog.save()
        messages.success(request,'导入成功，共导入%d行数据' %(row-1))    
        return HttpResponseRedirect('/serverimport')
    else:
        return render(request, 'assets/serverimport.html')

@login_required(login_url='/login/')
def networkdeviceimport(request):
    if request.POST:
      form = UploadExcelForm(request.POST, request.FILES)
      if form.is_valid():
        wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read())
        table = wb.sheets()[0]
        row = table.nrows
        for i in range(1, row):
            name = table.cell(i,0).value
            name = name.strip('\n')
            if table.cell(i,1).ctype == 1:#如果是字符串，去除回车
                sn = table.cell(i,1).value
                sn = sn.strip('\n')
            else:
                sn = table.cell(i,1).value
            networkdevice_type = table.cell(i,2).value
            hostname = table.cell(i,3).value
            hostname = hostname.strip('\n')
            business_unit_text = table.cell(i,4).value
            manufacturer = table.cell(i,5).value
            modelnumber = table.cell(i,6).value
            status_text = table.cell(i,7).value
            idc = table.cell(i,8).value
            machineRoom = table.cell(i,9).value
            cabinet = table.cell(i,10).value
            high = table.cell(i,11).value
            manage_ip = table.cell(i,12).value
            operation = table.cell(i,13).value
            reason = table.cell(i,14).value
            memo = table.cell(i,15).value
            if networkdevice_type == u'路由器':
               networkdevice_type = 0
            elif networkdevice_type == u'交换机':
               networkdevice_type = 1
            elif networkdevice_type == u'防火墙':
               networkdevice_type = 2
            elif networkdevice_type == u'DWDM':
               networkdevice_type = 3
            if business_unit_text == u'领骏':
                business_unit=0
            elif business_unit_text == u'驰联':
                business_unit=1
            if status_text == u'运营':
                status=0
            elif status_text == u'闲置':
                status=1
            elif status_text == u'待启用':
                status=2
            elif status_text == u'故障':
                status=3
            elif status_text == u'备用':
                status=4
            asset = models.Asset()
            if name:
                try:
                    tempnetworkdevice = get_object_or_404(models.Asset,name=name)
                except:
                    asset.name=name    
                else:
                    messages.error(request,'第%d行数据导入失败,固资号已经存在' %i)
                    return HttpResponseRedirect('/networkdeviceimport')                
            else:
                messages.error(request,'第%d行数据导入失败,固资号不能为空' %i)
                return HttpResponseRedirect('/networkdeviceimport')
            if sn:
                try:
                    tempnetworkdevice = get_object_or_404(models.Asset,sn=sn)
                except:
                    asset.sn=sn    
                else:
                    messages.error(request,'第%d行数据导入失败,固资号已经存在' %i)
                    return HttpResponseRedirect('/networkdeviceimport')                
            else:
                messages.error(request,'第%d行数据导入失败,SN不能为空' %i)
                return HttpResponseRedirect('/networkdeviceimport')           
            if idc:
                try:
                    idc_name = models.DataCenter.objects.get(name=idc)
                except:
                    messages.error(request,'第%d行数据导入失败,机房不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.idc = idc_name
            else:
                asset.idc = None            
            if machineRoom:
                try:
                    machineRoom_name = models.MachineRoom.objects.get(name=machineRoom)
                except:
                    messages.error(request,'第%d行数据导入失败,机房管理单元不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.machineRoom = machineRoom_name
            else:
                asset.machineRoom = None        
            if cabinet:
                try:
                    cabinet_name = models.Cabinet.objects.get(name=cabinet,machineroom = machineRoom_name)
                except:
                    messages.error(request,'第%d行数据导入失败,所在机房机架不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.cabinet = cabinet_name
            else:
                asset.cabinet = None        
            if modelnumber:
                try:
                    modelnumber_name = models.Modelnumber.objects.get(name=modelnumber)
                except:
                    messages.error(request,'第%d行数据导入失败,型号不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.modelnumber = modelnumber_name
            else:
                asset.modelnumber = None        
            if manufacturer:
                try:
                    manufacturer_name = models.Manufacturer.objects.get(name=manufacturer)
                except:
                    messages.error(request,'第%d行数据导入失败,厂商不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.manufacturer = manufacturer_name
            else:
                asset.manufacturer = None        
            if operation:
                try:
                    operation_name = User.objects.get(username=operation)
                except:
                    messages.error(request,'第%d行数据导入失败,维护人不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/networkdeviceimport')
                else:
                    asset.operation = operation_name
            else:
                asset.operation = None
            if manage_ip:
                asset.manage_ip = manage_ip
            else:
                asset.manage_ip = None    
            asset.asset_type = 'networkdevice'
            asset.business_unit=business_unit
            asset.hostname=hostname
            asset.status=status
            asset.high=high
            asset.memo=memo
            asset.save()
            networkdevice = models.NetworkDevice(networkdevice_type=networkdevice_type,asset=asset)
            networkdevice.save()
            detail=u'网络设备导入'
            eventlog = models.EventLog(asset=asset,event_type=0,reason=reason,detail=detail,user=request.user)
            eventlog.save()
        messages.success(request,'导入成功，共导入%d行数据' %(row-1))    
        return HttpResponseRedirect('/networkdeviceimport')
    else:
        return render(request, 'assets/networkdeviceimport.html')

@login_required(login_url='/login/')
def cabinetimport(request):
    if request.POST:
      form = UploadExcelForm(request.POST, request.FILES)
      if form.is_valid():
        wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read())
        table = wb.sheets()[0]
        row = table.nrows
        for i in range(1, row):
            cabinet = models.Cabinet()
            name = table.cell(i,0).value
            machineroom = table.cell(i,1).value
            cabinet.slotcount = table.cell(i,2).value
            user_text = table.cell(i,3).value
            status_text = table.cell(i,4).value
            cabinet.power = table.cell(i,5).value
            reason = table.cell(i,6).value
            cabinet.memo = table.cell(i,7).value
            if status_text == u'是':
                cabinet.status=0
            elif status_text == u'否':
                cabinet.status=1   
            if user_text == u'是':
                cabinet.user=0
            elif  user_text == u'否':
                cabinet.user=1
            if name:
                cabinet.name = name
            else:
                messages.error(request,'第%d行数据导入失败,机柜名不能为空' %i)
                return HttpResponseRedirect('/cabinetimport')
            if machineroom:
                try:
                    machineroom_name = models.MachineRoom.objects.get(name=machineroom)
                except:
                    messages.error(request,'第%d行数据导入失败,机房管理单元不存在' %i)
                    return HttpResponseRedirect('/cabinetimport')
                else:
                    try:
                        tempcabinet = get_object_or_404(models.Cabinet,machineroom=machineroom_name,name=name)
                    except:
                        cabinet.machineroom = machineroom_name
                        cabinet.datacenter = machineroom_name.datacenter
                    else:
                        messages.error(request,'第%d行数据导入失败,所在机房管理单元已存在该机柜' %i)
                        return HttpResponseRedirect('/cabinetimport')
            else:                
                messages.error(request,'第%d行数据导入失败,机房管理单元不能为空' %i)
                return HttpResponseRedirect('/cabinetimport')
            cabinet.save()
            detail=u'机柜导入'
            eventlog = models.EventLog(cabinet=cabinet,event_type=0,reason=reason,detail=detail,user=request.user)
            eventlog.save()
        messages.success(request,'导入成功，共导入%d行数据' %(row-1))    
        return HttpResponseRedirect('/cabinetimport')
    else:
        return render(request, 'assets/cabinetimport.html')


@login_required(login_url='/login/')
def datacenterimport(request):
    if request.POST:
      form = UploadExcelForm(request.POST, request.FILES)
      if form.is_valid():
        wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read())
        table = wb.sheets()[0]
        row = table.nrows
        for i in range(1, row):
            datacenter = models.DataCenter()
            name = table.cell(i,0).value
            datacenter.shortname = table.cell(i,1).value
            datacenter.isp = table.cell(i,2).value
            admin = table.cell(i,3).value
            datacenter.contactnumber = table.cell(i,4).value
            datacenter.address = table.cell(i,5).value
            reason = table.cell(i,6).value
            datacenter.memo = table.cell(i,7).value
            if name:
                try:
                    tempdatacenter = get_object_or_404(models.DataCenter,name=name)
                except:
                    datacenter.name = name    
                else:
                    messages.error(request,'第%d行数据导入失败,机房已经存在' %i)
                    return HttpResponseRedirect('/datacenterimport')    
            else:
                messages.error(request,'第%d行数据导入失败,机房名不能为空' %i)
                return HttpResponseRedirect('/datacenterimport')    
            if admin:
                try:
                    admin_name = User.objects.get(username=admin)
                except:
                    messages.error(request,'第%d行数据导入失败,维护人不存在，固资号%s' %(i,name))
                    return HttpResponseRedirect('/datacenterimport')
                else:
                    datacenter.admin = admin_name
            datacenter.save()
            detail=u'机房导入'
            eventlog = models.EventLog(datacenter=datacenter,event_type=0,reason=reason,detail=detail,user=request.user)
            eventlog.save()
        messages.success(request,'导入成功，共导入%d行数据' %(row-1))    
        return HttpResponseRedirect('/networkdeviceimport')
    else:
        return render(request, 'assets/datacenterimport.html')

@login_required(login_url='/login/')
def portimport(request,asset_id):
    if request.POST:
      form = UploadExcelForm(request.POST, request.FILES)
      if form.is_valid():
        wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
        table = wb.sheets()[0]
        row = table.nrows
        for i in range(1, row):
            port = models.Ports()
            hostname = table.cell(i,0).value
            name = table.cell(i,1).value
            port_status = table.cell(i,2).value
            port_type = table.cell(i,3).value
            port.connect_user = table.cell(i,4).value
            if port_status == u'运营':
               port.port_status=0
            elif port_status == u'闲置':
               port.port_status=1
            elif port_status == u'故障':
               port.port_status=2
            if port_type == u'网络设备互联':
               port.port_type = 0
            elif port_type == u'服务器互联':
               port.port_type = 1
            elif port_type == u'客户互联':
               port.port_type = 2 
            elif port_type == u'待定':
               port.port_type = 3
            if name == '':
               messages.error(request,'设备端口不能为空')
               return HttpResponseRedirect('/portimport/%s' %asset_id) 
            if hostname:
               try:
                  networkdevice = models.Asset.objects.get(hostname=hostname)
               except:
                  messages.error(request,'设备%s不存在' %hostname)
                  return HttpResponseRedirect('/portimport/%s' %asset_id)
               else:
                  try:
                      port = models.Ports.objects.get(name=name,networkdevice=networkdevice)
                  except:
                      port.name = name
                      port.networkdevice = networkdevice
                      port.save()
                  else:
                      messages.error(request,'设备%s已存在端口%s' %(hostname,name))
                      return HttpResponseRedirect('/portimport/%s' %asset_id)
            else:
               messages.error(request,'设备名不能为空')
               return HttpResponseRedirect('/portimport/%s' %asset_id) 
        messages.success(request,'导入成功，共导入%d个端口' %(row-1))
        return HttpResponseRedirect('/portimport/%s' %asset_id)   
      else:
          messages.error(request,'导入表格异常')
          return HttpResponseRedirect('/portimport/%s' %asset_id) 
    else:
        return render(request, 'assets/portimport.html')

@login_required(login_url='/login/')
def interconnectimport(request):
    if request.POST:
        form = UploadExcelForm(request.POST, request.FILES)
        if form.is_valid():
            wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
            table = wb.sheets()[0]
            row = table.nrows
            for i in range(1, row):
                hostname_a = table.cell(i,0).value
                port_a = table.cell(i,1).value
                hostname_z = table.cell(i,2).value
                port_z = table.cell(i,3).value
                port_type = table.cell(i,4).value
                if port_type == u'网络设备互联':
                    try:
                        networkdevice_a = models.Asset.objects.get(hostname=hostname_a)
                    except:
                        messages.error(request,'网络设备%s不存在' %hostname_a)
                        return HttpResponseRedirect('/interconnectimport')
                    else:
                        try:
                            port_a = models.Ports.objects.get(name=port_a,networkdevice=networkdevice_a)
                        except:
                            messages.error(request,'第%d行数据有误，设备%s不存在端口%s' %((row-1),hostname_a,port_a))
                            return HttpResponseRedirect('/interconnectimport')
                        else:
                            try:
                                networkdevice_z = models.Asset.objects.get(hostname=hostname_z)
                            except:
                                messages.error(request,'第%d行数据有误，设备名为空或%s不存在' %((row-1),hostname_z))
                                return HttpResponseRedirect('/interconnectimport')
                            else:
                                try:
                                    port_z = models.Ports.objects.get(name=port_z,networkdevice=networkdevice_z)
                                except:
                                    messages.error(request,'第%d行数据有误，设备%s不存在端口%s' %((row-1),hostname_z,port_z))
                                    return HttpResponseRedirect('/interconnectimport')
                                else:
                                    if (port_a.connect_port or port_z.connect_port):
                                        messages.error(request,'第%d行数据有误，设备端口已经与其他网络设备互联' %(row-1))
                                        return HttpResponseRedirect('/interconnectimport') 
                                    elif (port_a.connect_server or port_z.connect_server):
                                        messages.error(request,'第%d行数据有误，设备端口已经与其他服务器互联' %(row-1))
                                        return HttpResponseRedirect('/interconnectimport')     
                                    elif networkdevice_a == networkdevice_z:
                                        messages.error(request,'第%d行数据有误，设备不能与自己互联' %(row-1))
                                        return HttpResponseRedirect('/interconnectimport')
                                    else:
                                        port_a.port_type = 0
                                        port_z.port_type = 0
                                        port_a.connect_port =  port_z
                                        port_z.connect_port =  port_a
                                        port_a.save()
                                        port_z.save()       
                elif port_type == u'服务器互联':
                    try:
                        networkdevice_a = models.Asset.objects.get(hostname=hostname_a)
                    except:
                        messages.error(request,'第%d行数据有误，网络设备%s不存在' %((row-1),hostname_a))
                        return HttpResponseRedirect('/interconnectimport')
                    else:
                        try:
                            port_a = models.Ports.objects.get(name=port_a,networkdevice=networkdevice_a)
                        except:
                            messages.error(request,'第%d行数据有误，设备%s不存在端口%s' %((row-1),hostname_a,port_a))
                            return HttpResponseRedirect('/interconnectimport')
                        else:
                            try:
                                connect_server = models.Server.objects.get(asset__name=hostname_z)
                            except:
                                messages.error(request,'第%d行数据有误，服务器%s不存在' %((row-1),hostname_z))
                                return HttpResponseRedirect('/interconnectimport')
                            else:
                                port_a.port_type = 1
                                port_a.connect_server = connect_server
                                port_a.save()                                        
                else:
                    messages.error(request,'第%d行数据有误，连接类型错误：%s' %((row-1),port_type))
                    return HttpResponseRedirect('/interconnectimport')
            messages.success(request,'导入成功，共导入%d个端口' %(row-1))
            return HttpResponseRedirect('/interconnectimport') 
        else:
            messages.error(request,'导入表格异常')
            return HttpResponseRedirect('/portimport/%s' %asset_id) 
    else:
        return render(request, 'assets/interconnectimport.html') 

@login_required(login_url='/login/')
def assetimport(request,asset_type):
    if asset_type == '专线':
        if request.POST:
            form = UploadExcelForm(request.POST, request.FILES)
            if form.is_valid():
                wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
                table = wb.sheets()[0]
                row = table.nrows
                for i in range(1, row):
                    circuit = models.Circuit()
                    name = table.cell(i,0).value
                    name = name.strip('\n')
                    if table.cell(i,1).ctype == 1:#如果是字符串，去除回车
                        number = table.cell(i,1).value
                        number = number.strip('\n')
                    else:
                        number = table.cell(i,1).value
                    circuit_type = table.cell(i,2).value
                    circuit.bw = table.cell(i,3).value if table.cell(i,3).value else None
                    status = table.cell(i,4).value
                    circuit_business_unit = table.cell(i,5).value
                    self_use_status = table.cell(i,6).value
                    circuit.customer = table.cell(i,7).value
                    maintainer = table.cell(i,8).value
                    maintainer = maintainer.strip('\n')
                    circuit.vlan = table.cell(i,9).value if table.cell(i,9).value else None
                    circuit.isp = table.cell(i,10).value
                    circuit.isp_contacts = table.cell(i,11).value
                    circuit.isp_contacts_phonenumber = table.cell(i,12).value
                    circuit.circuit_lenth = table.cell(i,13).value if table.cell(i,13).value else None
                    circuit.attenuation = table.cell(i,14).value if table.cell(i,14).value else None
                    date_online = table.cell(i,15).value if table.cell(i,15).value else None
                    date_dismantle = table.cell(i,16).value if table.cell(i,16).value else None
                    machineroom_a = table.cell(i,17).value
                    cabinet_a = table.cell(i,18).value
                    networkdevice_a= table.cell(i,19).value
                    port_a = table.cell(i,20).value
                    machineroom_z = table.cell(i,21).value
                    cabinet_z = table.cell(i,22).value
                    networkdevice_z = table.cell(i,23).value
                    port_z = table.cell(i,24).value
                    circuit.cloudnumber = table.cell(i,25).value
                    circuit.router = table.cell(i,26).value
                    circuit.memo = table.cell(i,27).value
                    if date_online:
                       if table.cell(i,15).ctype == 3:
                          tempdate_online = xldate_as_tuple(date_online,0)
                          year = tempdate_online[0]
                          month = tempdate_online[1]
                          day = tempdate_online[2]
                          circuit.date_online = date(year,month,day)
                       else:
                          messages.error(request,'第%d行数据导入失败,启用日期格式错误' %i)
                          return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                       circuit.date_online = None
                    if date_dismantle:
                       if table.cell(i,16).ctype == 3:
                          tempdate_dismantle = xldate_as_tuple(date_dismantle,0)
                          year = tempdate_dismantle[0]
                          month = tempdate_dismantle[1]
                          day = tempdate_dismantle[2]
                          circuit.date_dismantle = date(year,month,day)
                       else:
                          messages.error(request,'第%d行数据导入失败,拆除日期格式错误' %i)
                          return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                       circuit.date_dismantle = None
                    if not name:
                       messages.error(request,'第%d行数据导入失败,专线命名不能为空' %i)
                       return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    if not number:
                       messages.error(request,'第%d行数据导入失败,专线编号不能为空' %i)
                       return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    if circuit_type == 'Fiber':
                        circuit.circuit_type = 0
                    elif circuit_type == 'DWDM':
                        circuit.circuit_type = 1
                    elif circuit_type == 'LAN':
                        circuit.circuit_type = 2
                    elif circuit_type == 'SDH':
                        circuit.circuit_type = 3 
                    if status == '运营':
                        circuit.status = 0
                    elif status == '拆除':
                        circuit.status = 1   
                    elif status == '待启用':
                        circuit.status = 2  
                    if circuit_business_unit == '领骏':
                        circuit.business_unit = 0
                    elif circuit_business_unit == '驰联':
                        circuit.business_unit = 1
                    if self_use_status == '是':
                        circuit.self_use_status = 0   
                    elif self_use_status == '否':
                        circuit.self_use_status = 1
                    try:
                        tempcircuit = get_object_or_404(models.Circuit,name=name)
                    except:
                        circuit.name = name
                    else:
                        messages.error(request,'第%d行数据导入失败,已存在%s专线' %(i,name))
                        return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                    try:
                        tempcircuit = get_object_or_404(models.Circuit,number=number)
                    except:
                        circuit.number = number
                    else:
                        messages.error(request,'第%d行数据导入失败,已存在%s专线' %(i,number))
                        return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                    if maintainer:
                        try:
                            tempmaintainer = User.objects.get(username=maintainer)
                        except:
                            messages.error(request,'第%d行数据导入失败,维护人%s不存在' %(i,maintainer))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            circuit.maintainer = tempmaintainer
                    else:
                        circuit.maintainer = None
                    if  machineroom_a:
                        try:
                            tempmachineroom_a = get_object_or_404(models.MachineRoom,name=machineroom_a)
                        except:
                            messages.error(request,'第%d行数据导入失败,机房%s不存在' %(i,machineroom_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                        else:
                            circuit.machineroom_a = tempmachineroom_a
                    else:
                        circuit.machineroom_a = None        
                    if  cabinet_a:
                        try:
                            tempcabinet_a = get_object_or_404(models.Cabinet,name=cabinet_a)
                        except:
                            messages.error(request,'第%d行数据导入失败,机房%s不存在' %(i,cabinet_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            circuit.cabinet_a = tempcabinet_a
                    else:
                        circuit.cabinet_a = None 
                    if  networkdevice_a:
                        try:
                            tempnetworkdevice_a = get_object_or_404(models.Asset,hostname=networkdevice_a)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            circuit.networkdevice_a = tempnetworkdevice_a
                    else:
                        circuit.networkdevice_a = None
                    if  port_a:
                        if tempnetworkdevice_a:
                            try:
                                tempport_a = get_object_or_404(models.Ports,name=port_a,networkdevice=tempnetworkdevice_a)
                            except:
                                messages.error(request,'第%d行数据导入失败,设备%s不存在端口%s' %(i,networkdevice_a,port_a))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                circuit.port_a = tempport_a
                        else:
                            messages.error(request,'第%d行数据导入失败,只有端口，没有设备' %i)
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                         circuit.port = None
                    if  machineroom_z:
                        try:
                            tempmachineroom_z = get_object_or_404(models.MachineRoom,name=machineroom_z)
                        except:
                            messages.error(request,'第%d行数据导入失败,机房%s不存在' %(i,machineroom_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                        else:
                            circuit.machineroom_z = tempmachineroom_z
                    else:
                        circuit.machineroom_z = None        
                    if  cabinet_z:
                        try:
                            tempcabinet_z = get_object_or_404(models.Cabinet,name=cabinet_z)
                        except:
                            messages.error(request,'第%d行数据导入失败,机房%s不存在' %(i,cabinet_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            circuit.cabinet_z = tempcabinet_z
                    else:
                        circuit.cabinet_z = None 
                    if  networkdevice_z:
                        try:
                            tempnetworkdevice_z = get_object_or_404(models.Asset,hostname=networkdevice_z)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            circuit.networkdevice_z = tempnetworkdevice_z
                    else:
                        circuit.networkdevice_z = None
                    if  port_z:
                        if tempnetworkdevice_z:
                            try:
                                tempport_z = get_object_or_404(models.Ports,name=port_z,networkdevice=tempnetworkdevice_z)
                            except:
                                messages.error(request,'第%d行数据导入失败,设备%s不存在端口%s' %(i,networkdevice_z,port_z))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                circuit.port_z = tempport_z
                        else:
                            messages.error(request,'第%d行数据导入失败,只有端口，没有设备' %i)
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                         circuit.port = None                                                                    
                    circuit.save()
                    detail = '专线导入'
                    eventlog = models.CircuitEventLog(circuit=circuit,event_type=0,detail=detail,user=request.user)
                    eventlog.save()
            messages.success(request,'导入成功，共导入%d行数据' %(row-1))
            return HttpResponseRedirect('/assetimport/%s' %asset_type)   
        else:
            return render(request, 'assets/assetimport.html',{'asset_type':asset_type})
    elif asset_type == 'DWDM':
        if request.POST:
            form = UploadExcelForm(request.POST, request.FILES)
            if form.is_valid():
                wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
                table = wb.sheets()[0]
                row = table.nrows
                for i in range(1, row):
                    dwdm = models.DWDM()
                    name = table.cell(i,0).value
                    modelnumber = table.cell(i,1).value
                    manufacturer = table.cell(i,2).value                    
                    dwdm.high = table.cell(i,3).value if table.cell(i,3).value else None
                    status = table.cell(i,4).value
                    business_unit = table.cell(i,5).value
                    dwdm.mux = table.cell(i,6).value if table.cell(i,6).value else None
                    dwdm.ba = table.cell(i,7).value if table.cell(i,7).value else None
                    dwdm.pa = table.cell(i,8).value if table.cell(i,8).value else None
                    dwdm.dcm = table.cell(i,9).value if table.cell(i,9).value else None
                    oeo = table.cell(i,10).value
                    olp = table.cell(i,11).value
                    maintainer = table.cell(i,12).value
                    machineroom_a = table.cell(i,13).value
                    cabinet_a = table.cell(i,14).value
                    device_a_number= table.cell(i,15).value
                    machineroom_z = table.cell(i,16).value
                    cabinet_z = table.cell(i,17).value
                    device_z_number = table.cell(i,18).value
                    dwdm.memo = table.cell(i,19).value
                    if name:
                        try:
                            tempdwdm = get_object_or_404(models.DWDM,name=name)
                        except:
                            dwdm.name = name
                        else:
                            messages.error(request,'第%d行DWDM数据导入失败,已存在%sDWDM名称' %(i,name))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)    
                    else: 
                        messages.error(request,'第%d行DWDM数据导入失败,DWDM名称不能为空' %i)
                        return HttpResponseRedirect('/assetimport/%s' %asset_type)  
                    if modelnumber:
                        try:
                            tempmodelnumber = get_object_or_404(models.Modelnumber,name=modelnumber)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,型号%s不存在' %(i,modelnumber))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            dwdm.modelnumber = tempmodelnumber 
                    else:        
                        dwdm.modelnumber = None
                    if manufacturer:
                        try:
                            tempmanufacturer = get_object_or_404(models.Manufacturer,name=manufacturer)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,厂商%s不存在' %(i,manufacturer))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            dwdm.manufacturer = tempmanufacturer
                    else:        
                        dwdm.manufacturer = None    
                    if status == '运营':
                        dwdm.status = 0
                    elif status == '拆除':
                        dwdm.status = 1   
                    elif status == '待启用':
                        dwdm.status = 2  
                    if business_unit == '领骏':
                        dwdm.business_unit = 0
                    elif business_unit == '驰联':
                        dwdm.business_unit = 1
                    if oeo == '是':
                        dwdm.oeo = 0   
                    elif oeo == '否':
                        dwdm.oeo = 1
                    if olp == '是':
                        dwdm.olp = 0   
                    elif olp == '否':
                        dwdm.olp = 1 
                    if maintainer:
                        try:
                            tempmaintainer = User.objects.get(username=maintainer)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,维护人%s不存在' %(i,maintainer))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            dwdm.maintainer = tempmaintainer
                    else:
                        dwdm.maintainer = None
                    if  machineroom_a:
                        try:
                            tempmachineroom_a = get_object_or_404(models.MachineRoom,name=machineroom_a)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,起始端机房管理单元%s不存在' %(i,machineroom_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                        else:
                            dwdm.machineroom_a = tempmachineroom_a
                    else:
                        dwdm.machineroom_a = None        
                    if  cabinet_a:
                        try:
                            tempcabinet_a = get_object_or_404(models.Cabinet,name=cabinet_a)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,机房不存在机架:%s' %(i,cabinet_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            dwdm.cabinet_a = tempcabinet_a
                    else:
                        dwdm.cabinet_a = None 
                    if  device_a_number:
                        try:
                            tempasset = get_object_or_404(models.Asset,name=device_a_number)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,起始端设备%s不存在' %(i,device_a_number))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            netowrkdevice = get_object_or_404(models.NetworkDevice,asset=tempasset)
                            if netowrkdevice.networkdevice_type == 3:
                                dwdm.device_a_number = tempasset
                            else:
                                messages.error(request,'第%d行DWDM数据导入失败,起始端设备%s不是波分设备' %(i,device_a_number))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                        dwdm.device_a_number = None
                    if  machineroom_z:
                        try:
                            tempmachineroom_z = get_object_or_404(models.MachineRoom,name=machineroom_z)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,终止端机房管理单元%s不存在' %(i,machineroom_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type) 
                        else:
                            dwdm.machineroom_z = tempmachineroom_z
                    else:
                        dwdm.machineroom_z = None        
                    if  cabinet_z:
                        try:
                            tempcabinet_z = get_object_or_404(models.Cabinet,name=cabinet_z)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,机房不存在机架:%s' %(i,cabinet_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            dwdm.cabinet_z = tempcabinet_z
                    else:
                        dwdm.cabinet_z = None 
                    if  device_z_number:
                        try:
                            tempasset = get_object_or_404(models.Asset,name=device_z_number)
                        except:
                            messages.error(request,'第%d行DWDM数据导入失败,终止端设备%s不存在' %(i,device_z_number))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            netowrkdevice = get_object_or_404(models.NetworkDevice,asset=tempasset)
                            if netowrkdevice.networkdevice_type == 3:
                                dwdm.device_z_number = tempasset
                            else:
                                messages.error(request,'第%d行DWDM数据导入失败,终止端设备%s不是波分设备' %(i,device_z_number))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                        dwdm.device_z_number = None
                    dwdm.save()
                    detail = 'DWDM导入'
            messages.success(request,'导入成功，共导入%d行数据' %(row-1))
            return HttpResponseRedirect('/assetimport/%s' %asset_type)   
        else:
            return render(request, 'assets/assetimport.html',{'asset_type':asset_type})
    elif asset_type == '波道':
        if request.POST:
            form = UploadExcelForm(request.POST, request.FILES)
            if form.is_valid():
                wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read()) 
                table = wb.sheets()[0]
                row = table.nrows
                for i in range(1, row):
                    channel = models.Channel()
                    name = table.cell(i,0).value
                    dwdm = table.cell(i,1).value
                    status = table.cell(i,2).value
                    channel.customer = table.cell(i,3).value
                    networkdevice_a = table.cell(i,4).value
                    port_a = table.cell(i,5).value
                    networkdevice_z = table.cell(i,6).value
                    port_z = table.cell(i,7).value
                    channel.memo = table.cell(i,8).value
                    if name:
                        if dwdm:
                            try:
                                tempdwdm = get_object_or_404(models.DWDM,name=dwdm)
                            except:
                                messages.error(request,'第%d行数据导入失败,DWDM:%s不存在' %(i,dwdm))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                try:
                                    tempchannel = get_object_or_404(models.Channel,name=name,dwdm=dwdm)
                                except:
                                    channel.name = name
                                    channel.dwdm = tempdwdm
                                else:
                                    messages.error(request,'第%d行数据导入失败,DWDM:%s已经存在名称为:%s的波道' %(i,dwdm,name))
                                    return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            messages.error(request,'第%d行数据导入失败,DWDM不能为空' %i)
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                        messages.error(request,'第%d行数据导入失败,波道名称不能为空' %i)
                        return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    if status == '运营':
                        channel.status = 0
                    elif status == '拆除':
                        channel.status = 1   
                    elif status == '待启用':
                        channel.status = 2
                    if  networkdevice_a:
                        try:
                            tempnetworkdevice_a = get_object_or_404(models.Asset,hostname=networkdevice_a)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            channel.networkdevice_a = tempnetworkdevice_a
                    else:
                        channel.networkdevice_a = None
                    if  port_a:
                        if tempnetworkdevice_a:
                            try:
                                tempport_a = get_object_or_404(models.Ports,name=port_a,networkdevice=tempnetworkdevice_a)
                            except:
                                messages.error(request,'第%d行数据导入失败,设备%s不存在端口%s' %(i,networkdevice_a,port_a))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                channel.port_a = tempport_a
                        else:
                            messages.error(request,'第%d行数据导入失败,只有端口，没有设备' %i)
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                         channel.port = None
                    if  networkdevice_z:
                        try:
                            tempnetworkdevice_z = get_object_or_404(models.Asset,hostname=networkdevice_z)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            channel.networkdevice_z = tempnetworkdevice_z
                    else:
                        channel.networkdevice_z = None
                    if  port_z:
                        if tempnetworkdevice_z:
                            try:
                                tempport_z = get_object_or_404(models.Ports,name=port_z,networkdevice=tempnetworkdevice_z)
                            except:
                                messages.error(request,'第%d行数据导入失败,设备%s不存在端口%s' %(i,networkdevice_z,port_z))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                channel.port_z = tempport_z
                        else:
                            messages.error(request,'第%d行数据导入失败,只有端口，没有设备' %i)
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                         channel.port = None
                    channel.save()
                    detail = 'DWDM导入'
            messages.success(request,'导入成功，共导入%d行数据' %(row-1))
            return HttpResponseRedirect('/assetimport/%s' %asset_type)                         
        else:            
            return render(request, 'assets/assetimport.html',{'asset_type':asset_type})
    elif asset_type == '网段':
       if request.POST:
           form = UploadExcelForm(request.POST, request.FILES)
           if form.is_valid():
               wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read())
               table = wb.sheets()[0]
               row = table.nrows
               for i in range(1, row):
                   ipnet = models.IpNet()
                   name = table.cell(i,0).value
                   gw_ip = table.cell(i,1).value if table.cell(i,1).value else None
                   ipnet.isp = table.cell(i,2).value
                   ipnet_status_text = table.cell(i,3).value
                   ipnet_type_text = table.cell(i,4).value
                   business_type = table.cell(i,5).value
                   ipnet.vlan = table.cell(i,6).value if table.cell(i,6).value else None
                   ipnet.ipnet_customer = table.cell(i,7).value
                   ipnet.memo = table.cell(i,8).value
                   if ipnet_status_text == u'运营':
                       ipnet.ipnet_status=0
                   elif ipnet_status_text == u'待分配':
                       ipnet.ipnet_status=1
                   elif ipnet_status_text == u'已分配':
                       ipnet.ipnet_status=2
                   elif ipnet_status_text == u'保留':
                       ipnet.ipnet_status=3   
                   if ipnet_type_text == u'业务网段':
                       ipnet.ipnet_type=0
                   elif ipnet_type_text == u'互联网段':
                       ipnet.ipnet_type=1
                   if business_type == u'IDC':
                       ipnet.business_type = 0
                   elif business_type == u'IXP':
                       ipnet.business_type = 1
                   elif business_type == u'管理':
                       ipnet.business_type = 2
                   if name:
                       try:
                           tempipnet = get_object_or_404(models.IpNet,name=name)
                       except:
                           ipnet.name = name    
                       else:
                           messages.error(request,'第%d行数据导入失败,网段已经存在' %i)
                           return HttpResponseRedirect('/assetimport/%s' %asset_type)  
                   else:
                       messages.error(request,'第%d行数据导入失败,网段名不能为空' %i)
                       return HttpResponseRedirect('/assetimport/%s' %asset_type)    
                   try:
                       IP(name)
                   except:
                       messages.error(request,'网段%s格式输入错误' %name)
                       return HttpResponseRedirect('/assetimport/%s' %asset_type)
                   else:
                       ipnet.netmask = IP(name).strNetmask()
                       if gw_ip and gw_ip not in IP(name):
                          messages.error(request,"网关%s不在网段内%s" %(gw_ip,name))
                          return HttpResponseRedirect('/assetimport/%s' %asset_type)
                       else:
                          ipnet.gw_ip = gw_ip
                          ipnet.split_status=1
                          ipnet.save()
                          ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=0,detail='网段导入',user=request.user)
                          ipeventlog.save()
               messages.success(request,"导入成功，共导入%d个网段" %(row-1))
               return HttpResponseRedirect('/assetimport/%s' %asset_type)
       else:
           return render(request, 'assets/assetimport.html',{'asset_type':asset_type})
    elif asset_type == '互联网段':
       if request.POST:
           form = UploadExcelForm(request.POST, request.FILES)
           if form.is_valid():
               wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['excel'].read())
               table = wb.sheets()[0]
               row = table.nrows
               for i in range(1, row):
                    conipnet = models.ConIpNet()
                    name = table.cell(i,0).value
                    ipnet_status_text = table.cell(i,1).value
                    ipnet_type_text = table.cell(i,2).value
                    zone = table.cell(i,3).value
                    conipnet.vlan = table.cell(i,4).value if table.cell(i,4).value else None
                    ip_a = table.cell(i,5).value
                    networkdevice_a = table.cell(i,6).value
                    conipnet.port_a = table.cell(i,7).value
                    ip_z = table.cell(i,8).value
                    networkdevice_z = table.cell(i,9).value
                    conipnet.port_z = table.cell(i,10).value
                    conipnet.usage = table.cell(i,11).value
                    conipnet.memo = table.cell(i,12).value
                    if ipnet_status_text == u'运营':
                        conipnet.ipnet_status=0
                    elif ipnet_status_text == u'待分配':
                        conipnet.ipnet_status=1
                    elif ipnet_status_text == u'已分配':
                        conipnet.ipnet_status=2
                    elif ipnet_status_text == u'保留':
                        conipnet.ipnet_status=3   
                    if ipnet_type_text == u'IDC':
                        conipnet.ipnet_type=0
                    elif ipnet_type_text == u'IXP':
                        conipnet.ipnet_type=1
                    elif ipnet_type_text == u'管理':
                        conipnet.ipnet_type=2  
                    if zone == u'上海': 
                        conipnet.zone = 0
                    elif zone == u'北京':  
                        conipnet.zone = 1
                    elif zone == u'广州': 
                        conipnet.zone = 2   
                    if name:
                        try:
                           tempipnet = get_object_or_404(models.IpNet,name=name)
                        except:
                           conipnet.name = name    
                        else:
                           messages.error(request,'第%d行数据导入失败,网段已经存在' %i)
                           return HttpResponseRedirect('/assetimport/%s' %asset_type)  
                    else:
                        messages.error(request,'第%d行数据导入失败,网段名不能为空' %i)
                        return HttpResponseRedirect('/assetimport/%s' %asset_type)    
                    try:
                        IP(name)
                    except:
                        messages.error(request,'第%d行数据导入失败,网段%s格式输入错误' %(i,name))
                        return HttpResponseRedirect('/assetimport/%s' %asset_type)
                    else:
                        if ip_a:
                            if ip_a not in IP(name):
                                messages.error(request,"第%d行数据导入失败,起始端IP:%s不在网段内%s" %(i,ip_a,name))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                conipnet.ip_a = ip_a
                        else:
                            conipnet.ip_a = None
                        if ip_z:
                            if ip_z not in IP(name):
                                messages.error(request,"第%d行数据导入失败,终止端IP:%s不在网段内%s" %(i,ip_a,name))
                                return HttpResponseRedirect('/assetimport/%s' %asset_type)
                            else:
                                conipnet.ip_z = ip_z
                        else:
                            conipnet.ip_z = None
                    if networkdevice_a:
                        try:
                            tempnetworkdevice = get_object_or_404(models.Asset,hostname=networkdevice_a)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_a))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            conipnet.networkdevice_a = tempnetworkdevice 
                    else:
                        conipnet.networkdevice_a = None
                    if networkdevice_z:
                        try:
                            tempnetworkdevice = get_object_or_404(models.Asset,hostname=networkdevice_z)
                        except:
                            messages.error(request,'第%d行数据导入失败,设备%s不存在' %(i,networkdevice_z))
                            return HttpResponseRedirect('/assetimport/%s' %asset_type)
                        else:
                            conipnet.networkdevice_z = tempnetworkdevice 
                    else:
                        conipnet.networkdevice_z = None
                    conipnet.save()
                    #ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=0,detail='网段导入',user=request.user)
                    #ipeventlog.save()
               messages.success(request,"导入成功，共导入%d个网段" %(row-1))
               return HttpResponseRedirect('/assetimport/%s' %asset_type)
       else:
           return render(request, 'assets/assetimport.html',{'asset_type':asset_type})
    else:
        return HttpResponse('访问网页不存在')